import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk, ImageOps
import os

from UI.ui.resultDisplay import MainWindow


class LoginFrame(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller
        self.db = controller.db

        # 页面标题
        label = tk.Label(self, text="登录", font=("Arial", 16))
        label.pack(pady=20)

        # 头像框
        self.avatar_label = tk.Label(self, text="头像", width=10, height=5)
        self.avatar_label.pack(pady=10)

        # 账号输入框
        self.account_label = tk.Label(self, text="账号/手机号")
        self.account_label.pack()
        # self.account_entry = tk.Entry(self)
        # self.account_entry.pack(pady=5)
        self.account_var = tk.StringVar()
        self.account_var.trace_add("write", self.on_account_input)  # 输入变化时触发

        self.account_entry = tk.Entry(self, textvariable=self.account_var)
        self.account_entry.pack(pady=5)

        # 密码输入框
        self.password_label = tk.Label(self, text="密码")
        self.password_label.pack()
        self.password_entry = tk.Entry(self, show="*")
        self.password_entry.pack(pady=5)

        self.container = tk.Frame(self)
        self.container.pack(pady=20)

        # 登录按钮
        self.login_button = tk.Button(self.container, text="登录", command=self.login)
        self.login_button.pack(side="left",padx=5)

        # 注册按钮
        self.register_button = tk.Button(self.container, text="注册", command=self.open_register_window)
        self.register_button.pack(side="left",padx=5)

        # 重置密码按钮
        self.reset_password_button = tk.Button(self, text="重置密码", command=self.reset_password)
        self.reset_password_button.pack(pady=10)

        self.current_avatar_img = None

    def on_account_input(self, *args):
        """账号输入框内容变化时触发"""
        account = self.account_var.get().strip()
        if not account:
            self.reset_avatar()
            return

        # 查询用户头像路径（支持账号或手机号）
        avatar_path = self.db.get_avatar_path(account)
        if avatar_path and os.path.exists(avatar_path):
            self.display_avatar(avatar_path)
        else:
            self.reset_avatar()

    def display_avatar(self, image_path):
        """加载并显示头像"""
        try:
            img = Image.open(image_path)
            img = ImageOps.exif_transpose(img)
            img = img.resize((100, 100), Image.Resampling.LANCZOS)  # 调整大小
            self.current_avatar_img = ImageTk.PhotoImage(img)
            self.avatar_label.config(image=self.current_avatar_img, text="",width=100,height=100,relief="solid")
        except Exception as e:
            print(f"加载头像失败: {e}")
            self.reset_avatar()

    def reset_avatar(self):
        """重置为默认状态"""
        self.avatar_label.config(image="", text="头像",width=10,height=5)
        self.current_avatar_img = None

    def login(self):
        account = self.account_entry.get()
        password = self.password_entry.get()
        if self.db.login(account, password):
            messagebox.showinfo("成功", "登录成功！")
            #self.controller.show_frame("MainWindow")
            self.controller.destroy()
            root=tk.Tk()
            app=MainWindow(root)
            root.mainloop()

        else:
            messagebox.showerror("错误", "登录失败，请检查账号和密码！")

    def open_register_window(self):
        self.controller.show_frame("RegisterFrame")

    def reset_password(self):
        account = self.account_entry.get()
        if self.db.reset_password(account):
            messagebox.showinfo("成功", "密码重置成功！")
        else:
            messagebox.showerror("错误", "密码重置失败，请检查账号是否存在！")
